<?php
namespace app\api\controller;
use think\facade\Cache;
use app\api\controller\Common;
use think\Db;

define('YUMING' , get_system('agency_system_yun_t_yuming'));//腾讯云域名
define('X_APPID' , 'wxfa284194ff2f9dc1');//小程序appid
define('X_SECRET' , '79e5f0b8bf3f4cea0043284cdfe809b4');//小程序密钥

class Index extends Common
{   
    //首页轮播
    public function slide(){
        $res = Db::query('select img from zltc_slide where slide_show = 1 order by time desc limit 3');

        $data = [];
        foreach($res as $k => $v){
            $data[$k] = $v['img'];
        }

        echo json_encode($data);
        exit;
    }

    //首页分类列表
    public function cateList(){
        $data = Db::name('house_cate')
            ->field('id , name , url , pic')
            ->where('cate_show' , 1)
            ->where('cid' , 0)
            ->order('id asc')
            ->select();

        foreach($data as $k => $v){
            if(mb_strlen($v['name']) > 4){
                $data[$k]['name'] = mb_substr($v['name'] , 0 , 4) . '...';
            }
        }
    	echo json_encode($data);
    	exit;
    }

    //授权
    public function login(){
        $data = $_POST;
        $info = [];
        $url      = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . X_APPID . '&secret='. X_SECRET . '&js_code=' . $data['code'] . '&grant_type=authorization_code';
        $res    = $this->http_get($url);
        $arr    = json_decode($res , true);

        $info['x_openid'] = $arr['openid'];
        $info['sex']      = $data['gender'];
        $info['nickname'] = $data['nickname'];
        $info['pic_user']      = $data['img'];
        $info['time']     = time();
        if(!Db::name('house_user')->where('x_openid' , $arr['openid'])->find()){
            $res = Db::name('house_user')->insert($info);
            if($res){
                return $this->ajaxReturn(['openid' => $arr['openid'],'pic'=>$info['pic_user'],'nickname'=>$info['nickname']]);
            }
        }else{
            return $this->ajaxReturn(['openid' => $arr['openid'],'pic'=>$info['pic_user'],'nickname'=>$info['nickname']]);
        }
    }

    //新盘推荐
    public function sinbanpo(){
        $data = Db::name('plat_info')
        ->where('plat_show',1)
        ->field('id , position ,title , etiquette , adresse , prix , pic')
        ->order('sort asc')
        ->limit(5)
        ->select();

        foreach($data as $k => $v){
            if(strstr($v['pic'] , ',')){
                $arr = explode(',' , $v['pic']);
                $data[$k]['pic'] = end($arr);
            }
            if(strstr($v['etiquette'] , ',')){
                $arr = explode(',' , $v['etiquette']);
                $data[$k]['etiquette'] = array_slice($arr , 0 , 3);
            }
        }

        echo json_encode($data);
        exit;
    }

    //精选二手房
    public function maison(){
        $data = Db::name('house_info')
        ->where('cid' , 1)
        ->where('info_examiner',2)
        ->where('info_show',1)
        ->field('id , position ,title, etiquette , adresse , prix , pic , mezzanine , aire , faire')
        ->order('sort asc')
        ->limit(5)
        ->select();

        foreach($data as $k => $v){
            if(strstr($v['pic'] , ',')){
                $arr = explode(',' , $v['pic']);
                $data[$k]['pic'] = end($arr);
            }
            if(strstr($v['etiquette'] , ',')){
                $arr = explode(',' , $v['etiquette']);
                $data[$k]['etiquette'] = array_slice($arr , 0 , 3);
            }else{
                $data[$k]['etiquette'] = [$v['etiquette']];
            }
            if($v['prix'] == 0){
                $data[$k]['position'] = mb_substr($v['position'] . $v['mezzanine'] . $v['aire'] . '㎡' . '售价面议' , 0 , 18);
            }else{
                $data[$k]['position'] = mb_substr($v['position'] . $v['mezzanine'] . $v['aire'] . '㎡' . '售价' . $v['prix'] . '元' , 0 , 18);
            }
        }

        echo json_encode($data);
        exit;
    }

    //精选出租房
    public function louer(){
        $data = Db::name('louer_info')
        ->where('cid' , 2)
        ->where('info_show',1)
        ->where('info_examiner',2)
        ->field('id , position , title , etiquette , adresse , prix , pic , mezzanine , aire , faire')
        ->order('sort asc')
        ->limit('5')
        ->select();

        foreach($data as $k => $v){
            if(strstr($v['pic'] , ',')){
                $arr = explode(',' , $v['pic']);
                $data[$k]['pic'] = end($arr);
            }
            if(strstr($v['etiquette'] , ',')){
                $arr = explode(',' , $v['etiquette']);
                $data[$k]['etiquette'] = array_slice($arr , 0 , 3);
            }else{
                $data[$k]['etiquette'] = [$v['etiquette']];
            }
            $data[$k]['position'] = mb_substr($v['position'] . $v['mezzanine'] . $v['aire'] , 0 , 18);
        }


        
        echo json_encode($data);
        exit;
    }

    public function ressource(){
        $data = Db::name('ressources_info')
        ->where('is_show',1)
        ->order('id desc')
        ->limit(3)
        ->select();

        foreach($data as $k => $v){
            $data[$k]['time'] = date('m-d' , $v['time']);
            $data[$k]['view'] = Cache::get('res_' . $v['id']);
        }
        echo json_encode($data);
        exit;
    }

    //出租房添加
    public function issue(){
        $data = $this->unInput('openid');
        $openid = $this->input('openid');
        $data['guan_id'] = Db::name('house_user')->where('x_openid',$openid)->value('id');
        $data['info_examiner'] = 2;
        $data['info_show'] = 1;
        $data['time'] = time();
        $data['cid'] = 2;
       
        if(isset($data['etiquette'])){
            $regex = "/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\.|\/|\;|\'|\`|\-|\=|\\\|\||/";
            $data['etiquette'] = preg_replace($regex,"",$data['etiquette']);
            $data['etiquette'] = preg_replace("/\"/","",$data['etiquette']);
            if(count($data['etiquette']) <= 3){
                $data['etiquette'] = $data['etiquette'];
            }else{
                return $this->ajaxReturn(2,'标签最多可选三个');
            }
        }
        if($data['faire'] == 1){
            $data['faire'] = '毛坯';
        }
        if($data['faire'] == 2){
            $data['faire'] = '中等装修';
        }
        if($data['faire'] == 0){
            $data['faire'] = '精装修';
        }
        $is = Db::name('louer_info')->insert($data);
        if($is){
            return $this->ajaxReturn(0,'操作成功');
        }else{
            return $this->ajaxReturn(1,'操作失败');
        }
    }
    
    //二手房添加
    public function used(){
        $data = $this->unInput('openid');
        $openid = $this->input('openid');
        $data['guan_id'] = Db::name('house_user')->where('x_openid',$openid)->value('id');
        $data['time'] = time();
        $data['cid'] = 1;
        if(isset($data['etiquette'])){
            $regex = "/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\.|\/|\;|\'|\`|\-|\=|\\\|\||/";
            $data['etiquette'] = preg_replace($regex,"",$data['etiquette']);
            $data['etiquette'] = preg_replace("/\"/","",$data['etiquette']);
            if(count($data['etiquette']) <= 3){
                $data['etiquette'] = implode(',' , $data['etiquette']);
            }else{
                return $this->ajaxReturn(2,'标签最多可选三个');
            }
        }
        if($data['faire'] == 1){
            $data['faire'] = '毛坯';
        }elseif($data['faire'] == 2){
            $data['faire'] = '中等装修';
        }elseif($data['faire'] == 0){
            $data['faire'] = '精装修';
        }
        $data['info_examiner'] = 2;
        $data['info_show'] = 1;
        $is = Db::name('house_info')->insert($data);
        if($is){
            return $this->ajaxReturn(0,'操作成功');
        }else{
            return $this->ajaxReturn(1,'操作失败');
        }
    }

    //商铺添加
    public function store(){
        $data = $this->unInput('openid');
        $openid = $this->input('openid');
        $data['guan_id'] = Db::name('house_user')->where('x_openid',$openid)->value('id');
        $data['time'] = time();
        $data['cid'] = 3;
        $data['plat_examiner'] = 2;
        $data['plat_show'] = 1;
        if(isset($data['etiquette'])){
            $regex = "/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\.|\/|\;|\'|\`|\-|\=|\\\|\||/";
            $data['etiquette'] = preg_replace($regex,"",$data['etiquette']);
            $data['etiquette'] = preg_replace("/\"/","",$data['etiquette']);
            if(count($data['etiquette']) <= 3){
                $data['etiquette'] = implode(',' , $data['etiquette']);
            }else{
                return $this->ajaxReturn(2,'标签最多可选三个');
            }
        }
        if(isset($data['manage'])){
            if($data['manage'] == 0){
                $data['manage_type'] = '酒楼餐饮';
            }
            if($data['manage'] == 1){
                $data['manage_type'] = '美容美发';
            }
            if($data['manage'] == 2){
                $data['manage_type'] = '服饰鞋包';
            }
            if($data['manage'] == 3){
                $data['manage_type'] = '休闲娱乐';
            }
            if($data['manage'] == 4){
                $data['manage_type'] = '百货超市';
            }
            if($data['manage'] == 5){
                $data['manage_type'] = '生活服务';
            }
            if($data['manage'] == 6){
                $data['manage_type'] = '电子设备';
            }
            if($data['manage'] == 7){
                $data['manage_type'] = '旅店宾馆';
            }
            if($data['manage'] == 8){
                $data['manage_type'] = '其他';
            }
        }
        if(isset($data['genre'])){
            if($data['genre'] == 0){
               $data['genre_type'] = '商业街卖场';
            }
            if($data['genre'] == 1){
               $data['genre_type'] = '写字楼配套';
            }
            if($data['genre'] == 2){
               $data['genre_type'] = '住宅底商';
            }
            if($data['genre'] == 3){
               $data['genre_type'] = '摊位柜台';
            }
            if($data['genre'] == 4){
               $data['genre_type'] = '其他';
            }
        }
        $is = Db::name('house_store')->insert($data);
        if($is){
            return $this->ajaxReturn(0,'操作成功');
        }else{
            return $this->ajaxReturn(1,'操作失败');
        }
    }

    public function upload()
    {
        $tmp_name = $_FILES['pic']["tmp_name"];
        $ymd = date('Y_m_d');
        
        $file_str = '/web/images/tmp/';
        $name_file = time().mt_rand(111,999);

        if(!file_exists(".".$file_str)){
            mkdir(".".$file_str);
        }

        $pic_str = '';
        if(file_exists($tmp_name)){
            $type = explode('.',$_FILES['pic']["name"]);
            $pic_str = $name_file.'.'.$type[count($type)-1];
            move_uploaded_file($tmp_name,".".$file_str.$pic_str);
        }

        $cosClient = new \Qcloud\Cos\Client(array('region' => get_default('yun_t_diqu'),'credentials'=> array(
            'secretId'    => get_default('yun_t_appid'),
            'secretKey' =>  get_default('yun_t_key'))));
        $result = $cosClient->Upload(
            get_default('yun_t_shuitong'),
            $pic_str,
            fopen(".".$file_str.$pic_str, 'rb'));
        unlink(".".$file_str.$pic_str);

        if($pic_str){
            echo $pic_str;die;
        }else{
            echo '';die;
        }
    }

    //买房添加
    public function message(){
        $data = input();
        $data['time'] = time();
        $is = Db::name('house_message')->insert($data);
        if($is){
            return $this->ajaxReturn(0,'操作成功');
        }else{
            return $this->ajaxReturn(1,'操作失败');
        }
    }

    public function sellhouse(){
        $data = input();
        $data['time'] = time();
        $is = Db::name('house_sellhouse')->insert($data);
        if($is){
            return $this->ajaxReturn(0,'操作成功');
        }else{
            return $this->ajaxReturn(1,'操作失败');
        }
    }

  	public function poster(){
        $id = input('param.id',0);
        $type = input('param.type',0);
        if($id&&$type){
            //echo $this->code($id,$type);
            return $this->ajaxReturn(1,'',['type'=>1,'img'=>$this->code($id,$type)])
        }else{
            $is = Db::name('house_poster')->where('banner_is_show',1)->value('img_url');
            return $this->ajaxReturn($is);
        }
    }

    //生成小程序码
    
     public function code($id=1,$type=1){
        $APPID = X_APPID;
        $AppSecret = X_SECRET;
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$APPID."&secret=".$AppSecret."";
        $arr = $this->ihttp_post($url,'');
        $arr = json_decode($arr,true);
        $access_token = $arr['access_token'];

        //小程序码
        $res = $this->getWxcode($access_token,$id,$type);
        return $res;
        // dump($arr);
        // dump($access_token);
        exit;
    }

    public function api_notice_increment($url, $data){
      $ch = curl_init();
      // $header = array('Accept-Charset: utf-8');
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
      // curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
      curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
      curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      $tmpInfo = curl_exec($ch);
         
      if (curl_errno($ch)) {
        return false;
      }else{
        // var_dump($tmpInfo);
        return $tmpInfo;
      }
    }

    /**
     * demo
     * @return [type] [description]
     */
    public function getWxcode($ACCESS_TOKEN,$id,$type){
        $url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$ACCESS_TOKEN;
        $post_data=
        array(
            'page'=>'pages/detail/plat',
            'scene'=>'9999999'//34%2CS853EE4QRP
        );
        $post_data=json_encode($post_data);
        $data=$this->send_post($url,$post_data);
        $result=$this->data_uri($data,'image/png');
        return '<image src='.$result.'></image>';
    }
    /**
     * 消息推送http
     * @param $url
     * @param $post_data
     * @return bool|string
     */
    protected function send_post($url, $post_data ) {
        $options = array(
            'http' => array(
                'method'  => 'POST',
                'header'  => 'Content-type:application/json',
                //header 需要设置为 JSON
                'content' => $post_data,
                'timeout' => 60
                //超时时间
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url,false,$context);
        return $result;
    }
    //二进制转图片image/png
    public function data_uri($contents, $mime)
    {
        $base64   = base64_encode($contents);
        return ('data:' . $mime . ';base64,' . $base64);
    }



    public function msgList(){
        $data = [];
        $plat_info = Db::name('plat_info')->where('plat_show',1)->select();
        if($plat_info){
            foreach($plat_info as $k => $v){
                $data['title'][] = $v['title'];
            }
        }
        $plat_info = Db::name('house_info')->where('info_show',1)->where('info_examiner',2)->select();
        if($plat_info){
            foreach($plat_info as $k => $v){
                $data['title'][] = $v['title'];
            }
        }
        $plat_info = Db::name('louer_info')->where('info_show',1)->select();
        if($plat_info){
            foreach($plat_info as $k => $v){
                $data['title'][] = $v['title'];
            }
        }
        $plat_info = Db::name('house_store')->where('plat_show',1)->select();
        if($plat_info){
            foreach($plat_info as $k => $v){
                $data['title'][] = $v['title'];
            }
        }
        return $this->ajaxReturn($data);

    }

    public function token(){
        $data = input();
        $url = 'https://api.weixin.qq.com/cgi-bin/token?appid=' . X_APPID . '&secret='. X_SECRET . '&grant_type=client_credential';
        $res = $this->http_get($url);
        $arr = json_decode($res,true);
        session_start();
        $_SESSION['access_token'] = $arr['access_token'];
        $_SESSION['expires_in'] = $arr['expires_in'];
        // $urls = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$_SESSION['access_token'];
        $ACCESS_TOKEN = "";
        if(!isset($_SESSION['access_token']) || (isset($_SESSION['expires_in']) && time() > $_SESSION['expires_in']))
        {
            $res = $this->http_get($url);
            $arr = json_decode($res,true); 
            $_SESSION['access_token'] = $arr['access_token'];
            $_SESSION['expires_in'] = time()+7200;
            $ACCESS_TOKEN = $arr["access_token"]; 
        }else{
            $ACCESS_TOKEN = $_SESSION["access_token"]; 
        }
        return $this->ajaxReturn($ACCESS_TOKEN);
    }

    public function getwxacodeunlimit(){
        $data = input();
        dump($data);die;
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$data['access_token'].'&path='.$data['page'].'&scene='.$data['scene'];
        $res = $this->ihttp_post($url);
        $arr = json_decode($res,true);
        var_dump($arr);die;
    }
}